home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2003 March / DPPCPRO0303.ISO / Components / Microsoft ASP / _SETUP.1 / MSDBQuery.inc < prev    next >
Encoding:
Text File  |  1998-11-20  |  21.3 KB  |  609 lines

  1. <!--#INCLUDE FILE="MSGlobal.inc"-->
  2. <!--#INCLUDE FILE="Adojavas.inc"-->
  3. <SCRIPT RUNAT=SERVER LANGUAGE=JSCRIPT>
  4. ////////////////////////////////////////////////////////////////////
  5. //                                                                //
  6. //   Fusion ASP Components                                        //
  7. //   Custom JScript Object: MSDBQuery                                // 
  8. //                                                                //
  9. ////////////////////////////////////////////////////////////////////
  10. /*
  11. Object:       MSDBQuery  
  12.  
  13. Version:      1.0  10/2/97
  14.  
  15. Written By:   Application Methods, Inc. 
  16.               6300 Southcenter Blvd.
  17.               Seattle, WA 98188
  18.               (206) 244-2400
  19.               http://www.appmethods.com
  20.  
  21. Description:  The MSDBQuery object is responsible for assembling an SQL query from 
  22.    four parameters and creating a cursor that can be used by database aware 
  23.    objects that require a cursor.  The parameters are broken up so that the individual
  24.    portions may be modified or built upon for the final SQL query that the cursor will
  25.    be based upon.
  26.  
  27. Note:   Generation of a number of hidden fields is necessary to pass information
  28.    on to other components.  All hidden fields created by this object are prefixed
  29.    with 'amaspHidden_' or 'amaspComponent_'.  Devlopers should never create
  30.    any form element with these prefixes or unexpected results will occur.
  31.  
  32. Properties:
  33.    name - the name of the query component 
  34.    dataSource - The name of the MSDBConnection object the query object is bound to
  35.    usePreviousQuery - Uses previous query if one found?
  36.    select - The "SELECT" portion of a SQL query
  37.    from - the "FROM" portion of a SQL query
  38.    where - the "WHERE" portion of a SQL query
  39.    orderBy - the "ORDER BY" portion of a SQL query
  40.  
  41. Methods:
  42.    buildSQL         - Builds SQL, adding passed constraints to the where clause and concatenating the 4 parts
  43.    buildWhere       - Builds the SQL "where" clause from user entered property and key fields passed in via the Request object
  44.    closeCursor      - Performs checks for null and closes recordset object
  45.    emitProperties   - Writes out all properties of the object to the page on which the object exists.
  46.    getCurrentCursor - Returns either the current recordset if it exists or a new, initialized recordset (calling openCursor and initializeCursor)
  47.    getQueryParams   - Resets the object's query parameters (select, from, where, order by)
  48.                       to those stored in client object from a previous query if "Use Previous Query"
  49.                       is set to true.  Otherwise, copies it's query parameters to the client object's
  50.                       select, from, where and order by properties for potential use by some other DBQuery
  51.                       object on another page
  52.    getURLStr        - Return value of old URL string from a previous list page
  53.    initializeCursor - Checks the isCursorInitialized property.  If False moves recordset to next record and sets property to true
  54.    isCursorEnd      - Detects end of record set
  55.    isCursorStart    - Detect beginning of record set
  56.    isNavigating     - Determines whether or not we are currently in the midst of navigating a recordset
  57.    moveNext         - Advances the cursor forward the number of records indicated. 
  58.    movePrevious     - Advances the cursor backwards the number of records indicated. 
  59.    openCursor       - Creates a new recordset
  60.    setCursor        - Replaces the current cursor for both this.cursor and Session(this.name) with the recordset object passed into the method
  61.    setURLStr        - Stores value of old URL string from a previous list page
  62.  
  63. USAGE:
  64.  
  65.  <SERVER>
  66.  
  67.  test = new DatabaseConnection("INFORMIX","","ol_tahoma","informix","informix","sysmaster",true);
  68.  test.connect();
  69.  
  70.  // Pass in parameters for SQL statement:  
  71.  //    select * from myTable where customerID > 7 order by lastname
  72.  theQuery = new MSDBQuery("MSDBQuery1", "MSDBConnection1", "*", "myTable", "customerID > 7", "lastname");
  73.  
  74.  theQuery.getCurrentCursor();
  75.  // Initialize the cursor, which will advance it to the first row of data
  76.  if (theQuery.initializeCursor())
  77.     write("The cursor was was advanced to the first row.");
  78.  else
  79.     write("The cursor contained no rows and could not be advanced");
  80.       
  81.  write("Customer last name is: " + theQuery.cursor.lastname);
  82.  
  83.  </SERVER>
  84.  
  85.  
  86.  
  87. =====================================================================*/
  88.  
  89. //
  90. // MSDBQuery Object Constructor
  91. //
  92. function MSDBQuery (name, dataSource, usePreviousQuery, select, from, where, orderBy) {
  93.    
  94.    // create a version of the request object that has none of the default properties
  95.    var strippedRequest = new NewRequest();
  96.    var newReq = new Object();
  97.    newReq = strippedRequest.newRequest;
  98.  
  99.    // Properties
  100.    this.name = (name != null) ? name : "";
  101.    this.newReq = new Object();
  102.    this.newReq = newReq;
  103.    this.usePreviousQuery = (usePreviousQuery == "true") ? true : false;
  104.    this.select = (select != null) ? select : "";
  105.    this.from = (from != null) ? from : "";
  106.    this.where = (where != null) ? where : "";
  107.    this.orderBy = (orderBy != null) ? orderBy : "";   
  108.    this.dataSource = dataSource;
  109.    
  110.    this.listActive = false;
  111.    this.URLString = "";
  112.    this.oldURLString = "";        // Holds the old URLString from a previous list page
  113.    this.matchType = "";
  114.  
  115.    // get the value of the variable
  116.    // called match_type (sent from the AdHoc button)
  117.    this.matchType = Request("amaspHidden_matchType") + "";
  118.          
  119.    this.cursor = null;      // Initialize cursor property to null
  120.    this.cursorPosition = 0;
  121.    this.sql = null;         // Set current sql property to null
  122.    this.isCursorInitialized = false;
  123.    this.matchStart = "";
  124.    this.matchAll = "";
  125.    this.matchParm = "";
  126.    
  127.    this.sessionQueryName = "DBQuery";    // will not work with multiplie queries on a page
  128.    
  129.    // Methods
  130.    this.buildSQL = quBuildSQL;
  131.    this.buildWhere = quBuildWhere;
  132.    this.getCurrentCursor = quGetCurrentCursor;
  133.    this.initializeCursor = quInitializeCursor;
  134.    this.openCursor = quOpenCursor;
  135.    this.getQueryParams = quGetQueryParams;
  136.    this.closeCursor = quCloseCursor;
  137.    this.emitProperties = quEmitProperties;
  138.    this.moveNext = quMoveNext;
  139.    this.movePrevious = quMovePrevious;
  140.    this.isNavigating = quIsNavigating;
  141.    this.setCursor = quSetCursor;
  142.    this.isCursorEnd = quIsCursorEnd;
  143.    this.isCursorStart = quIsCursorStart;
  144.    this.getURLStr = quGetURLStr;
  145.    this.setURLStr = quSetURLStr;
  146.       
  147.    if (this.isNavigating()) {
  148.            // current cursor is located in Session(this.name) & we need to move it per request params
  149.             i = 0;
  150.             this.cursorPosition = parseInt(Request.QueryString("amaspHidden_NavPosition"), 10);
  151.             count = parseInt(Request.QueryString("amaspHidden_NavCount"), 10);
  152.             
  153.             // Don't navigate if the current cursor position is the same as the last cursor position
  154.             if (this.cursorPosition == Session(this.sessionQueryName + "CursorPosition"))
  155.                 count = 0;
  156.             else
  157.                 Session(this.sessionQueryName + "CursorPosition") = this.cursorPosition;
  158.                 
  159.             if (isNaN(count))
  160.                 count=0;
  161.             direction = Request.QueryString("amaspHidden_NavDir") + "";
  162.             if (direction == void(0)+"")
  163.                 direction = "";
  164.             else
  165.                 direction = direction.toUpperCase();
  166.                 
  167.             while ((i < count) && !Session(this.sessionQueryName).EOF && !Session(this.sessionQueryName).BOF) {
  168.                 if (direction == "NEXT")
  169.                    Session(this.sessionQueryName).MoveNext();    // Navigate to proper position
  170.                else if (direction == "PREVIOUS") 
  171.                    Session(this.sessionQueryName).MovePrevious();
  172.                i++;
  173.            } // end while        
  174.    } // end if
  175.    else
  176.        Session(this.sessionQueryName + "CursorPosition") = 0;
  177.     
  178.     this.setURLStr();  // store old URL string temporarily for use by DBNav
  179.  
  180. }  // END Query constructor
  181.  
  182. // Method - quEmitProperties()
  183. // Emits all the object's properties.  Used as a debuging tool to verify correct
  184. // manipulation of the object.
  185.  
  186. function quEmitProperties ()
  187. {
  188.       debug("Writing MSDBQuery properties...");
  189.       write("\n<BR><B>MSDBQuery Properties:</B>");
  190.       write("\n<BR>usePreviousQuery = " + this.usePreviousQuery);
  191.       write("\n<BR>select = " + this.select);
  192.       write("\n<BR>from = " + this.from);
  193.       write("\n<BR>where = " + this.where);
  194.       write("\n<BR>orderBy = " + this.orderBy);
  195.       write("<BR>");
  196.  }   //End quEmitProperties;
  197.  
  198.  
  199. //
  200. // Build the SQL statement from each user-entered piece
  201. //
  202. function quBuildSQL () {
  203.  
  204.    this.getQueryParams();
  205.  
  206.    this.matchParm = "";   // reset all SQL building params to blank
  207.    this.matchAll = "";
  208.    this.matchStart = "";
  209.  
  210.    // Start building the basic SQL statement.
  211.    var sql = "";
  212.    sql = "select " + this.select + " ";
  213.    sql += "from " + this.from + " ";
  214.     
  215.    // Construct the where clause
  216.    var tempWhere = this.buildWhere();
  217.    if (tempWhere.length > 0)
  218.       tempWhere = "where " + tempWhere;
  219.  
  220.    sql += tempWhere;
  221.  
  222.    if (this.orderBy != "")
  223.       sql += " order by " + this.orderBy;
  224.  
  225.    return sql;
  226. }  // END quBuildSQL
  227.  
  228.  
  229. //
  230. // Builds the SQL 'where' clause from user entered expressions
  231. // and key fields passed in from another page (if any)
  232. //
  233. function quBuildWhere() {
  234.    
  235.    // make sure the where clause is a string.
  236.    var where = this.where + "";
  237.    
  238.    var URLString = "";
  239.    var pre = "amaspHidden_";       // Designator required to hide fields from the DBQuery object
  240.    var fieldPre = "amaspField_";   // Designator required for NewRequest object
  241.    var myDataType  = "";
  242.    var myDelim = "";
  243.    var myDate;
  244.       
  245.  
  246.       // Set the baseline match Parm
  247.    if ((this.matchType != "contains") && (this.matchType != "starts with")) 
  248.       this.matchParm = " = ";
  249.    
  250.    // Set the match parm to look for any instance of the string in 
  251.    // the field   
  252.    if (this.matchType == "contains")
  253.    {
  254.       this.matchParm = " like ";   
  255.       this.matchAll = "%"
  256.       this.matchStart = "%";         
  257.    }
  258.    
  259.    // Set the match parm to look for a string starting with
  260.    // the requested value      
  261.    if (this.matchType == "starts with")
  262.    {
  263.       this.matchParm = " like ";   
  264.       this.matchStart = "%";   
  265.    }
  266.      
  267.    // If a where clause exists, and keyFieldCount > 0
  268.    // Wrap the existing where clause in parens.   
  269.    if (where.length > 0)
  270.       where = "(" + where + ")";
  271.  
  272.    // Loop through the stripped request object, filtering out
  273.    // any other properties that must be filtered out of the where clause and the match
  274.    // type param.
  275.    for (var i in this.newReq)
  276.    {
  277.       // Ignore request object properties that contain certain special strings
  278.       // beginning with a prefix defined by the variable "pre" above
  279.       if ((i.indexOf(pre) < 0)) {    
  280.             // Look in new request object for hidden datatype indicator for this field   
  281.             myDataType = this.newReq[pre + i + "_dataType"];
  282.          
  283.             if (myDataType == null)  {
  284.                myDataType = "string";
  285.                debug("***Warning! Data type not found for field : " + i + ". Using default type string.");
  286.             }
  287.                                           
  288.             // if where already exists then append the new where with an AND clause
  289.             if (where.length > 0) where += " AND " ;                           
  290.             if (myDataType == "string") {
  291.                 // Only String types may be matched in ways other than exact match.
  292.                 where +=  i + this.matchParm + wrapDelim(this.connectionType, 
  293.                          myDataType, this.matchAll + this.newReq[i] + this.matchStart);                           
  294.             } 
  295.             else {
  296.                 where +=  i + " = " + wrapDelim(this.connectionType, myDataType, this.newReq[i]);                           
  297.             }
  298.  
  299.                         
  300.             // Build URL string
  301.             // Includes name of field, it's URL encoded value and it's data type.
  302.             // This value get's passed via the client object to the DBNav component for
  303.             // returning to the UP page properly.
  304.             if (URLString.length > 0)
  305.                URLString += "&" + fieldPre + i + "=" + escape(this.newReq[i]) + "&" + pre + i + "_dataType=" + escape(myDataType);
  306.             else
  307.                URLString = fieldPre + i + "=" + escape(this.newReq[i]) + "&" + pre + i + "_dataType=" + escape(myDataType);
  308.             this.URLString = URLString + "&amaspHidden_matchType=" + escape(this.matchType);
  309.  
  310.          } // end "if ((i.indexOf(".x") < 0) && ... "
  311.    } // end for loop
  312.   
  313.    return where;
  314.  
  315. }  // END quBuildWhere
  316.  
  317.  
  318. //
  319. // Returns the current cursor, if already established,
  320. // otherwise it attempts to open the cursor and return it.
  321. //
  322. function quGetCurrentCursor() {
  323.  
  324.    this.connectionType = "";
  325.    this.ODBCDatabaseType = "";
  326.    // Session properties are set by DBConnection object in it's constructor method for use here
  327.    // !!! NOTE: This code relies upon the DBConnection constructor being called before this method
  328.    // Temp Removed for good reason but kept for safe keeping
  329.    //if ((Session("amaspHidden_databaseType") != null) && (Session("amaspHidden_databaseType") != "null"))
  330.    //   this.connectionType = Session("amaspHidden_databaseType");
  331.    //else if ((Application("databaseType") != null) && (Application("databaseType") != "null"))
  332.    //   this.connectionType = Application("databaseType");
  333.    
  334.    //if ((Session("amaspHidden_ODBCDatabaseType") != null) && (Session("amaspHidden_ODBCDatabaseType") != "null"))
  335.    //   this.ODBCDatabaseType = Session("amaspHidden_ODBCDatabaseType");
  336.    //else if ((Application("ODBCDatabaseType") != null) && (Application("ODBCDatabaseType") != "null"))
  337.    //   this.ODBCDatabaseType = Application("ODBCDatabaseType");
  338.  
  339.    // Session properties are set by DBConnection object in it's constructor method for use here
  340.    // !!! NOTE: This code relies upon the DBConnection constructor being called before this method
  341.       this.connectionType   = Session("databaseType");
  342.       this.ODBCDatabaseType = Session("ODBCDatabaseType");
  343.  
  344.      // If navigating, don't recreate a new query.  Instead, use the one stored
  345.       // in the Session variable which has maintained its current position for the
  346.       // purpose of continuous navigation across client requests.
  347.  
  348.     if (this.cursor == null)
  349.           return this.openCursor();
  350.       else
  351.           return this.cursor;
  352.  
  353. }  // END quGetCurrentCursor
  354.  
  355.  
  356. //
  357. // Advances the cursor once to point to the first record in the set.
  358. // Sets the "isCursorInitialized" property to true if successfully initialized.
  359. //
  360. function quInitializeCursor() {
  361.    if (this.cursor != null)
  362.       if (!this.isCursorInitialized)
  363.           // Check for an empty recordset
  364.          if (!this.cursor.EOF && !this.cursor.BOF)
  365.             this.isCursorInitialized = true;
  366.    
  367.    return (this.isCursorInitialized);
  368.  
  369. }  // END quInitializeCursor
  370.  
  371.  
  372. //
  373. // Attempts to open the cursor on the database with an SQL 
  374. // statement generated by the "buildSQL" method
  375. //
  376. function quOpenCursor( sql ) {
  377. //   debug("Note: Opening MSDBQuery cursor...");
  378.  
  379.    var ODBCDatabaseType = "";
  380.    
  381.    // Temp Removed for good reason but kept for safe keeping
  382.    //if ((Session("amaspHidden_ODBCDatabaseType") != null) && (Session("amaspHidden_ODBCDatabaseType") != "null"))
  383.    ODBCDatabaseType = Session("ODBCDatabaseType");
  384.  
  385.       if ((sql == null) || (sql == void(0))) {
  386.          sql = this.buildSQL();
  387.          this.sql = sql;
  388.    }
  389.  
  390.     if (!this.isNavigating()) {
  391.         this.cursor = Server.CreateObject("ADODB.Recordset");
  392.         // adOpenDynamic (== 2) defined in Adojavas.inc - opens a dynamic cursor
  393.         this.cursor.Open(sql, Session(this.dataSource), adOpenDynamic); 
  394.       Session(this.sessionQueryName) = void(0);  // eliminate the old variable
  395. //        killit(this.sessionQueryName);
  396.       Session(this.sessionQueryName) = this.cursor; // store recordset in Session variable
  397.    } else
  398.        this.cursor = Session(this.sessionQueryName);    // if navigating, copy Session cursor into this.cursor
  399.    //}
  400.    
  401.    return this.cursor;   
  402.  
  403. }  // END quOpenCursor
  404.  
  405.  
  406.  
  407. //
  408. // Close the query's cursor object
  409. // Note:  Care must be used with this method.  Closing a cursor that's already closed
  410. // will crash the web server.
  411. //
  412. function quCloseCursor() {
  413.  
  414. //   debug("Note: Closing MSDBQuery cursor...");
  415.  
  416.    // Check to make sure we're not closing a cursor that isn't open or is already closed.
  417.    if ((this.cursor != null) && (!this.isNavigating())) {
  418. //      this.cursor.Close();
  419.        this.cursor = null;
  420.        this.isCursorInitialized = false;
  421.    }
  422.    
  423. }  // END quCloseCursor
  424.  
  425.  
  426.  
  427. //
  428. // Sets and returns query parameters to be used for this query
  429. // if "Use Previous Query" has been set to true
  430. //
  431. function quGetQueryParams() {
  432.    
  433.    // Constant representing the "hidden" prefix for special values passed in via URL
  434.    // or form variables to Request object
  435.    var PRE = "amaspHidden_";   
  436.  
  437.    // Initialization code
  438.    // If set to use the previous query from a list, initialize with values set in the Request object
  439.    // by the previous page's query object.   
  440.    // Also sets the "listActive" flag to true so other objects, such as the DBNav object,
  441.    // can detect if the query from a previous list is being navigated.
  442.  
  443.    if (this.usePreviousQuery && (this.newReq[PRE + "listActive"] != null) &&
  444.          (this.newReq[PRE + "listActive"] == "true") ) {
  445.       this.listActive = true;
  446.       this.select = Session("select");
  447.       this.from = Session("from")
  448.       this.where = Session("where")   // set it to where + "hidden" where (from passed in key fields)
  449.       this.orderBy = Session("orderBy")
  450.    } else {
  451.       Session("select") = this.select;
  452.       Session("from") = this.from;
  453.       Session("where") = this.buildWhere();
  454.       Session("orderBy") = this.orderBy;
  455.    }
  456.    
  457. } // END quGetQueryParams
  458.  
  459.  
  460. //
  461. // Advances the cursor forward the number of records indicated
  462. // Returns the number of records actually moved.  Returns 0 if at EOF.
  463. // 
  464. function quMoveNext( count ) {
  465.  
  466.     var i = 0;
  467.  
  468.     // Error check the input value
  469.     if (!IsNum(count))
  470.         count = 0;
  471.  
  472.     while(this.cursor != null && !this.cursor.eof && (i < count)) {
  473.         this.cursor.MoveNext();
  474.         i++;
  475.     }
  476.         
  477.     return i;    // return the number of records actually moved
  478.  
  479. } // end quMoveNext
  480.  
  481.  
  482. //
  483. // Moves the cursor backward the number of records indicated
  484. // 
  485. function quMovePrevious( count ) {
  486.  
  487.     var i = 0;
  488.     
  489.     // Error check the input value
  490.     if (!IsNum(count))
  491.         count = 0;
  492.         
  493.     while(this.cursor != null && !this.cursor.BOF && (i < count)) {
  494.         this.cursor.MovePrevious();
  495.         i++;
  496.     }
  497.     
  498.     return i;    // return the number of records actually moved
  499.  
  500. } // end quMovePrevious
  501.  
  502.  
  503. //
  504. // Determines whether or not we are currently in the midst of navigating a recordset.
  505. // 
  506. function quIsNavigating() {
  507.  
  508.     // If Request("amaspHidden_NavDir") was not present on the most recent request,
  509.     // then we must not be navigating, or are at the very start of navigating.  In 
  510.     // either such case, return "false" to indicate we are not in the midst of navigating
  511.     // the recordset.
  512.     if ((Request("amaspHidden_NavDir")+"" == (void(0)+"")) || Request("amaspHidden_NavDir") == null) 
  513.         return false;
  514.     else 
  515.         return true;
  516.         
  517. } // end quIsNavigating
  518.  
  519.  
  520. //
  521. // Replaces the current cursor for both this.cursor and Session(this.name) with
  522. // the recordset object passed into the method.
  523. //
  524. function quSetCursor ( theRecordset ) {
  525.  
  526.     // Make sure the recordset exists
  527.     if( (theRecordset != null) && (theRecordset != void(0)) ) {
  528.         this.cursor = theRecordset;
  529.         Session(this.sessionQueryName) = theRecordset;
  530.     }
  531.     
  532. } // end quSetCursor
  533.  
  534.  
  535. // 
  536. // Detect end of record set
  537. //
  538. function quIsCursorEnd () {
  539.  
  540.     if (this.cursor.EOF)
  541.         return true;
  542.     else
  543.         return false;
  544.         
  545. } // end quIsCursorEnd
  546.  
  547.  
  548. // 
  549. // Detect end of record set
  550. //
  551. function quIsCursorStart () {
  552.  
  553.     if (this.cursor.BOF)
  554.         return true;
  555.     else
  556.         return false;
  557.         
  558. } // end quIsCursorStart
  559.  
  560.  
  561. function quSetURLStr () {
  562.  
  563.     var oldvalue = "";
  564.     
  565.   // If the URL query string hasn't been set, set it based
  566.    // on URL query string currently stored in Session("URLStr")
  567.    if ( !this.isNavigating()) {
  568.        // If Session("URLStr") is blank or Request("amaspHidden_URLStr") is blank, initialize Session("URLStr")
  569.        // Need to blank on Request("amaspHidden_URLStr") is blank to make sure that coming back from a detail
  570.        // nav to a list nav doesn't keep around the detail key field params and throw off list navigation.
  571.       if ((Session("URLStr") == "") || (Session("URLStr") == "null") || (Session("URLStr") == null) || 
  572.               (Request.QueryString("amaspHidden_URLStr")+"" == "") ) 
  573.          Session("URLStr") = "amaspHidden_URLStr=";
  574.       // keep value around before we overwrite it below
  575.       this.oldURLStr = Session("URLStr") + "";
  576.    } else
  577.        this.oldURLStr = Request.QueryString("amaspHidden_URLStr");
  578.    
  579.     this.buildWhere();   // has a side effect that sets property this.URLString
  580.    // overwrite old URLStr value in Session object
  581.    Session("URLStr") = this.URLString;   
  582.    
  583.  
  584.    return this.oldURLStr;
  585.    
  586. } // end quSetURLStr
  587.  
  588.  
  589. // 
  590. // Return value of old URL string from a previous list page
  591. //
  592. function quGetURLStr() {
  593.  
  594.     return this.oldURLStr;
  595.  
  596. } // end quGetURLStr
  597.  
  598. </SCRIPT>
  599.  
  600. <SCRIPT RUNAT=SERVER LANGUAGE=VBSCRIPT>
  601. Sub killit (str)
  602.  
  603.     On Error Resume Next
  604.     Session(str).Close
  605.     set Session(str) = Nothing
  606.     Response.write("killed")
  607.  
  608. End Sub
  609. </SCRIPT>